package com.captain.special.二叉树.中等;

import com.captain.leetcode.TreeNode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Des:
 *
 * @author XL
 * @Date 2022/5/15 11:53
 */
public class 恢复二叉搜索树99 {
    List<TreeNode> ans = new ArrayList<>();

    public void recoverTree(TreeNode root) {
        recur(root);
        TreeNode p = null;
        TreeNode q = null;
        for (int i = 0; i < ans.size() - 1; i++) {
            //3 2 1  则 1和3进行交换
            if (ans.get(i).val > ans.get(i + 1).val) {
                //说明存在错误的数据
                q = ans.get(i + 1);
                if (p == null) {
                    p = ans.get(i);
                }
            }
        }
        if (q != null && p != null) {
            int qVal = q.val;
            q.val = p.val;
            p.val = qVal;
        }
    }
    public void recur(TreeNode node) {
        if (node == null) {
            return;
        }
        recur(node.left);
        ans.add(node);
        recur(node.right);
    }
}
